public class 实验三状态机 {

    public static class TrafficLightStateMachine {

        // 状态接口
        interface TrafficLightState {
            void handle(TrafficLightStateMachine context);
        }

        // 红灯状态
        private class RedLight implements TrafficLightState {
            @Override
            public void handle(TrafficLightStateMachine context) {
                System.out.println("红灯转为绿灯");
                context.setState(new GreenLight());
            }
        }

        // 绿灯状态
        private class GreenLight implements TrafficLightState {
            @Override
            public void handle(TrafficLightStateMachine context) {
                System.out.println("绿灯转为黄灯");
                context.setState(new YellowLight());
            }
        }

        // 黄灯状态
        private class YellowLight implements TrafficLightState {
            @Override
            public void handle(TrafficLightStateMachine context) {
                System.out.println("黄灯转为红灯");
                context.setState(new RedLight());
            }
        }

        // 当前状态
        private TrafficLightState state;

        // 构造函数，设置初始状态为红灯
        public TrafficLightStateMachine() {
            this.state = new RedLight();
        }

        // 改变状态的方法
        public void changeState() {
            state.handle(this);
        }

        // 设置新状态的方法
        public void setState(TrafficLightState state) {
            this.state = state;
        }

        // 启动状态机
        public void startStatus() {
            TrafficLightStateMachine trafficLight = new TrafficLightStateMachine();

            // 模拟几个状态的变化
            for (int i = 0; i < 5; i++) {
                trafficLight.changeState();
            }
        }
    }

    public static void main(String[] args) {
        TrafficLightStateMachine trafficLightStateMachine = new TrafficLightStateMachine();
        trafficLightStateMachine.startStatus();
    }
}
